package com.fishingwithme.android.ui.components

import android.net.Uri
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Close
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.alpha
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import coil.compose.AsyncImage
import coil.request.ImageRequest
import com.fishingwithme.android.ui.theme.AppDimensions
import com.fishingwithme.android.utils.ImageUtils
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File

/**
 * 带滚动条的LazyRow，确保可以滚动到最右侧
 */
@Composable
fun <T> LazyRowWithFullScrollbar(
    items: List<T>,
    modifier: Modifier = Modifier,
    listState: androidx.compose.foundation.lazy.LazyListState = rememberLazyListState(),
    itemContent: @Composable (T) -> Unit
) {
    // 使用传入的listState或创建新的

    // 计算滚动条的可见性
    val scrollbarAlpha by remember {
        derivedStateOf {
            if (listState.layoutInfo.totalItemsCount == 0) 0f
            else if (listState.canScrollForward || listState.canScrollBackward) 1f
            else 0f
        }
    }

    // 计算滚动条滑块的宽度比例
    val viewportRatio by remember {
        derivedStateOf {
            if (listState.layoutInfo.totalItemsCount == 0) 1f
            else {
                val visibleWidth = listState.layoutInfo.visibleItemsInfo.sumOf { it.size }
                val totalWidth =
                    listState.layoutInfo.totalItemsCount * (140 + AppDimensions.SPACING_12.value) // 每个item宽度+间距，使用实际尺寸
                (visibleWidth.toFloat() / totalWidth).coerceIn(0.1f, 1f)
            }
        }
    }

    // 计算滚动条位置
    val scrollPosition by remember {
        derivedStateOf {
            if (listState.layoutInfo.totalItemsCount == 0) 0f
            else {
                val firstVisibleIndex = listState.firstVisibleItemIndex
                val firstVisibleOffset = listState.firstVisibleItemScrollOffset

                // 使用简化的计算方式，每个item固定为140dp，间距使用StyleConstants定义的值
                val itemWidth = AppDimensions.ICON_SIZE_140.value
                val itemSpacing = AppDimensions.SPACING_12.value
                val imageCount = listState.layoutInfo.totalItemsCount
                val totalWidth = itemWidth * imageCount + itemSpacing * (imageCount - 1)
                val visibleWidth = listState.layoutInfo.viewportSize.width

                if (totalWidth <= visibleWidth) 0f
                else {
                    val scrollProgress =
                        ((firstVisibleIndex * (itemWidth + itemSpacing)) + firstVisibleOffset) /
                                (totalWidth - visibleWidth).toFloat()
                    scrollProgress.coerceIn(0f, 1f)
                }
            }
        }
    }

    Box(modifier = modifier) {
        // 主体LazyRow
        LazyRow(
            state = listState,
            modifier = Modifier.fillMaxWidth(),
            contentPadding = PaddingValues(end = AppDimensions.SPACING_12)
        ) {
            itemsIndexed(items) { _, item -> itemContent(item) }
        }

        // 滚动条
        if (scrollbarAlpha > 0f) {
            Surface(
                modifier = Modifier
                    .align(Alignment.BottomCenter)
                    .fillMaxWidth()
                    .height(AppDimensions.SPACING_4)
                    .alpha(scrollbarAlpha),
                color = Color.Transparent
            ) {
                Box(
                    modifier = Modifier
                        .align(Alignment.CenterStart)
                        .fillMaxWidth(viewportRatio)
                        .height(AppDimensions.SPACING_4)
                        .background(
                            color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.5f),
                            shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_2)
                        )
                        .graphicsLayer {
                            translationX = ((1 - viewportRatio) * scrollPosition * 100f).dp.toPx()
                        }
                )
            }
        }
    }
}

/**
 * 表示显示项的密封类，确保类型安全
 */
sealed class DisplayItem {
    data class ImageItem(val url: String) : DisplayItem()
    object AddButton : DisplayItem()
}

/**
 * 通用图片上传组件
 * @param pictures 图片URL列表
 * @param onPicturesChanged 图片列表变化的回调函数
 * @param maxImages 最大上传数量，默认为6
 * @param onImageUpload 图片上传的回调函数
 */
@Composable
fun ImageUploader(
    pictures: List<String>,
    onPicturesChanged: (List<String>) -> Unit,
    maxImages: Int = 6,
    onImageUpload: suspend (file: File) -> Flow<Result<String>>
) {
    val context = LocalContext.current
    val isUploading = remember { mutableStateOf(false) }
    val currentPictures = remember { mutableStateListOf(*pictures.toTypedArray()) }
    val selectedImageIndex = remember { mutableStateOf(0) } // 跟踪当前选中的图片索引

    // 观察pictures变化，自动更新组件
    LaunchedEffect(pictures) {
        currentPictures.clear()
        currentPictures.addAll(pictures)
    }

    val imagePickerLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        uri?.let {
            isUploading.value = true

            // 使用ImageUtils压缩图片
            val compressedFile = ImageUtils.compressImage(context, uri)
            compressedFile?.let { file ->
                // 上传文件
                CoroutineScope(Dispatchers.IO).launch {
                    onImageUpload(file).collect { result ->
                        CoroutineScope(Dispatchers.Main).launch {
                            result.fold(
                                onSuccess = { url ->
                                    currentPictures.add(url)
                                    onPicturesChanged(currentPictures.toList())
                                },
                                onFailure = { e ->
                                    // 可以添加错误处理逻辑
                                    e.printStackTrace()
                                }
                            )
                            isUploading.value = false
                        }
                    }
                }
            } ?: run {
                // 压缩失败，尝试使用原始方式
                // 将Uri转换为File
                val file = File(context.cacheDir, "temp_image_${System.currentTimeMillis()}.jpg")
                context.contentResolver.openInputStream(uri)?.use { inputStream ->
                    file.outputStream().use { outputStream ->
                        inputStream.copyTo(outputStream)
                    }
                }

                // 上传文件
                CoroutineScope(Dispatchers.IO).launch {
                    onImageUpload(file).collect { result ->
                        CoroutineScope(Dispatchers.Main).launch {
                            result.fold(
                                onSuccess = { url ->
                                    currentPictures.add(url)
                                    onPicturesChanged(currentPictures.toList())
                                },
                                onFailure = { e ->
                                    // 可以添加错误处理逻辑
                                    e.printStackTrace()
                                }
                            )
                            isUploading.value = false
                        }
                    }
                }
            }
        }
    }

    // 获取LazyRow的状态，用于自动滚动
    val listState = rememberLazyListState()

    Column(modifier = Modifier.fillMaxWidth()) {
        // 大图预览区域 - 减小高度并优化性能
        if (currentPictures.isNotEmpty()) {
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(AppDimensions.CARD_HEIGHT_150) // 减小预览图高度以提高性能
                    .background(MaterialTheme.colorScheme.surfaceVariant)
                    .clip(RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8))
            ) {
                // 根据选中的索引显示对应图片
                val displayIndex = minOf(selectedImageIndex.value, currentPictures.size - 1)
                // 使用简单的Box包裹AsyncImage，避免不支持的参数
                Box(modifier = Modifier.fillMaxSize()) {
                    AsyncImage(
                        model = ImageRequest.Builder(context)
                            .data(currentPictures[displayIndex])
                            .crossfade(true)
                            .size(400, 300) // 限制图片大小，减少内存占用
                            .build(),
                        contentDescription = "大图预览",
                        contentScale = ContentScale.Crop,
                        modifier = Modifier.fillMaxSize()
                    )
                }
            }
        } else {
            // 没有图片时显示更简洁的提示
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .height(AppDimensions.CARD_HEIGHT_150)
                    .background(MaterialTheme.colorScheme.surfaceVariant)
                    .clip(RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8))
                    .clickable { if (!isUploading.value) imagePickerLauncher.launch("image/*") },
                contentAlignment = Alignment.Center
            ) {
                Column(
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Icon(
                        imageVector = Icons.Default.Add,
                        contentDescription = "添加图片",
                        tint = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.size(AppDimensions.ICON_SIZE_32)
                    )
                    Text(
                        text = "点击上传图片",
                        style = MaterialTheme.typography.bodyLarge,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        textAlign = TextAlign.Center,
                        modifier = Modifier.padding(top = AppDimensions.SPACING_8)
                    )
                }
            }
        }

        Spacer(modifier = Modifier.height(AppDimensions.SPACING_20)) // 合理的间距

        // 图片项之间的间距
        val itemSpacing = AppDimensions.SPACING_12

        // 创建一个包含所有图片和添加按钮的组合列表 - 使用类型安全的DisplayItem
        val displayItems by remember {
            derivedStateOf {
                val items = mutableListOf<DisplayItem>()
                // 添加所有图片项
                items.addAll(currentPictures.map { DisplayItem.ImageItem(it) })
                // 添加图片按钮作为最后一个元素
                if (currentPictures.size < maxImages) {
                    items.add(DisplayItem.AddButton)
                }
                items
            }
        }

        // 确保每次图片列表更新后，滚动条自动滚动到最右侧，保证上传按钮可见
        LaunchedEffect(displayItems) {
            if (displayItems.isNotEmpty()) {
                withContext(Dispatchers.Main) {
                    // 等待布局完成后再滚动
                    listState.animateScrollToItem(displayItems.size - 1)
                }
            }
        }

        // 传递listState给LazyRowWithFullScrollbar
        LazyRowWithFullScrollbar(
            items = displayItems,
            listState = listState,
            modifier = Modifier.fillMaxWidth()
        ) { item ->
            when (item) {
                is DisplayItem.ImageItem -> {
                    // 显示图片项
                    val index = currentPictures.indexOf(item.url)
                    if (index != -1) {
                        Box(modifier = Modifier.padding(end = itemSpacing)) {
                            ImageItem(
                                imageUrl = item.url,
                                onRemove = {
                                    currentPictures.removeAt(index)
                                    onPicturesChanged(currentPictures.toList())
                                    // 如果删除的是当前选中的图片，重新设置选中索引
                                    if (selectedImageIndex.value == index && currentPictures.isNotEmpty()) {
                                        selectedImageIndex.value =
                                            minOf(index, currentPictures.size - 1)
                                    }
                                },
                                onClick = { selectedImageIndex.value = index } // 点击小图时更新大图显示
                            )
                        }
                    }
                }

                is DisplayItem.AddButton -> {
                    // 显示添加图片按钮
                    Box(modifier = Modifier.padding(end = itemSpacing)) {
                        AddImageButton(
                            onClick = { imagePickerLauncher.launch("image/*") },
                            isLoading = isUploading.value
                        )
                    }
                }
            }
        }

        // 图片数量提示
        Text(
            text = "已上传 ${currentPictures.size}/${maxImages} 张",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            modifier = Modifier.padding(top = AppDimensions.SPACING_8)
        )
    }

    // 上传中对话框
    if (isUploading.value) {
        Dialog(
            onDismissRequest = {},
            properties = androidx.compose.ui.window.DialogProperties(
                dismissOnBackPress = false,
                dismissOnClickOutside = false
            )
        ) {
            Card(
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_16),
                modifier = Modifier
                    .width(AppDimensions.CARD_HEIGHT_200)
                    .padding(AppDimensions.SPACING_16)
            ) {
                Column(
                    horizontalAlignment = Alignment.CenterHorizontally,
                    verticalArrangement = Arrangement.spacedBy(AppDimensions.SPACING_12),
                    modifier = Modifier.padding(AppDimensions.SPACING_16)
                ) {
                    CircularProgressIndicator()
                    Text("上传中...")
                }
            }
        }
    }
}

/**
 * 添加图片按钮组件
 */
@Composable
private fun AddImageButton(
    onClick: () -> Unit,
    isLoading: Boolean
) {
    Box(
        modifier = Modifier
            .size(AppDimensions.ICON_SIZE_100) // 增加添加按钮尺寸，与小图保持一致
            .background(
                MaterialTheme.colorScheme.surfaceVariant,
                RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            )
            .border(
                width = AppDimensions.BORDER_WIDTH_2,
                color = MaterialTheme.colorScheme.primary,
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            ) // 添加边框
            .clickable(enabled = !isLoading, onClick = onClick),
        contentAlignment = Alignment.Center
    ) {
        if (isLoading) {
            CircularProgressIndicator(
                modifier = Modifier.size(AppDimensions.ICON_SIZE_24),
                strokeWidth = AppDimensions.BORDER_WIDTH_2
            )
        } else {
            Icon(
                imageVector = Icons.Default.Add,
                contentDescription = "添加图片",
                tint = MaterialTheme.colorScheme.onSurfaceVariant,
                modifier = Modifier.size(AppDimensions.ICON_SIZE_24)
            )
        }
    }
}

/**
 * 图片项组件 - 移除排序功能，优化点击与滑动交互
 */
@Composable
private fun ImageItem(
    imageUrl: String,
    onRemove: () -> Unit,
    onClick: () -> Unit
) {
    val context = LocalContext.current

    Box(
        modifier = Modifier
            .size(AppDimensions.ICON_SIZE_100) // 增加小图尺寸
            .border(
                width = AppDimensions.BORDER_WIDTH_2,
                color = MaterialTheme.colorScheme.outline,
                shape = RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8)
            ) // 添加边框
            .clip(RoundedCornerShape(AppDimensions.ROUNDED_CORNER_8))
            .clickable { onClick() }
    ) {
        AsyncImage(
            model = ImageRequest.Builder(context)
                .data(imageUrl)
                .crossfade(true)
                .build(),
            contentDescription = "上传的图片",
            contentScale = ContentScale.Crop,
            modifier = Modifier.size(AppDimensions.ICON_SIZE_120)
        )
        // 删除按钮
        Box(
            modifier = Modifier
                .align(Alignment.TopEnd)
                .background(
                    Color.Black.copy(alpha = 0.5f),
                    RoundedCornerShape(bottomStart = AppDimensions.ROUNDED_CORNER_8)
                )
                .clickable(onClick = onRemove)
                .padding(AppDimensions.SPACING_4)
        ) {
            Icon(
                imageVector = Icons.Default.Close,
                contentDescription = "删除图片",
                tint = Color.White,
                modifier = Modifier.size(AppDimensions.ICON_SIZE_16)
            )
        }
    }
}